package ycl.security.handler;

import cn.hutool.core.collection.CollUtil;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.security.web.authentication.WebAuthenticationDetails;
import org.springframework.stereotype.Service;
import ycl.common.ApiResult;
import ycl.common.constants.ExceptionConstant;
import ycl.common.constants.SecurityConstant;
import ycl.common.models.res.LoginUser;
import ycl.common.utils.ServletUtil;
import ycl.security.feign.SystemFeign;
import ycl.security.service.LoginService;
import ycl.system.entity.SysPermission;
import ycl.system.entity.SysUser;
import ycl.system.mapper.SysUserMapper;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

/**
 * 认证成功
 *
 * @author ycl
 * @date 2022-03-09 14:14:38
 */
@Service("authSuccessHandler")
@Slf4j
public class AuthSuccessHandler implements AuthenticationSuccessHandler {

	@Resource
	private SysUserMapper sysUserMapper;
	@Resource
	private SystemFeign systemService;
	@Resource
	private LoginService loginService;

	/**
	 * 认证
	 *
	 * @param request        req
	 * @param response       res
	 * @param authentication auth
	 */
	@Override
	public void onAuthenticationSuccess(
			HttpServletRequest request,
			HttpServletResponse response,
			Authentication authentication) throws IOException {

		//认证对象身份, 返回验证主体
		User user = (User) authentication.getPrincipal();
		//获取当前用户信息
		WebAuthenticationDetails details = (WebAuthenticationDetails) authentication.getDetails();
		//获取用户名
		String username = user.getUsername();
		//获取远程地址
		String remoteAddress = details.getRemoteAddress();

		//获取用户
		SysUser sysUser = loginService.getUserByUsername(username);

		//查询用户的权限
		ApiResult<String> result;
		ApiResult<List<SysPermission>> permissionResult = systemService.selectPermissionByUserId(sysUser.getId());
		log.info("AuthSuccessHandler -- onAuthenticationSuccess -- permissionResult ====> {}", permissionResult);
		if (permissionResult.isSuccess()) {
			List<SysPermission> permissions = permissionResult.getData();
			if (CollUtil.isEmpty(permissions)) {//用户没有权限
				//throw new LoginException(LoginExceptionConstant.USER_NOT_PERMISSION);
				result = ApiResult.fail(ExceptionConstant.USER_NOT_PERMISSION);
				writeResponse(response, result);
				return;
			}
		}
		String loginType = request.getHeader(SecurityConstant.LOGIN_TYPE);
		LoginUser login = loginService.login(sysUser, loginType, remoteAddress);
		String token = login.getToken();
		result = ApiResult.success(token);
		JSONObject jsonObject = JSONObject.parseObject(JSONObject.toJSONString(result));
		jsonObject.put("user", sysUser);
		ServletUtil.setResultResponse(response);
		response.getWriter().write(JSONObject.toJSONString(jsonObject));
	}

	private <T> void writeResponse(HttpServletResponse response, ApiResult<T> result) throws IOException {
		JSONObject jsonObject = JSONObject.parseObject(JSONObject.toJSONString(result));
		ServletUtil.setResultResponse(response);
		response.getWriter().write(JSONObject.toJSONString(jsonObject));
	}
}
